package com.google.code.sharecontent.action;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Begin;
import org.jboss.seam.annotations.End;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Out;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.annotations.security.Restrict;

import com.google.code.sharecontent.model.Resource;
import com.google.code.sharecontent.model.ResourceDisplay;
import com.google.code.sharecontent.model.Status;
import com.google.code.sharecontent.model.User;

@Scope(ScopeType.CONVERSATION)
@Name("myresources")
public class MyResourcesAction extends BaseAction {

	String newResourcesName = null;
	
	@In("daoAction")
	private DaoAction daoAction;
	
	@In
	User user;
	
	@Restrict("#{s:hasRole('ADVANCED.USER')}")
	public void addNewResources() {
		try {
		log.info("addNewResources");
		if (this.newResourcesName != null && this.newResourcesName.length()>0) {
//			Status statusAdded = this.daoAction.getStatusDao().getByCode(Status.AUTH);
			Status statusAdded = this.daoAction.getStatusDao().getByCode(Status.ADDED);
			log.info("status"+statusAdded);
			/**
			 * TODO validate url
			 */
			Resource resourceNew = new Resource();
			resourceNew.setName(this.newResourcesName);
			resourceNew.setUrl(this.newResourcesName);
			resourceNew.setStatusId(statusAdded.getId());
			resourceNew.setUserId(user.getId());
			this.daoAction.getResourceDao().save(resourceNew);
		}
		} catch (Exception e1) {
			log.error(e1.getMessage());
			;
		}
		/**
		 * TODO ERROR!
		 */
	}
	
	public List<ResourceDisplay> getResources() {
		List<ResourceDisplay> listResult = new ArrayList<ResourceDisplay>();
		try {
			List<Resource> list = this.daoAction.getResourceDao().list();
			for (Resource resource : list) {
				ResourceDisplay resourceDisplay = new ResourceDisplay(resource);
				Status status;
				status = this.daoAction.getStatusDao().get(resource.getStatusId());
				resourceDisplay.setStatus(status.getName());
				User user = this.daoAction.getUserDao().get(resource.getUserId());
				resourceDisplay.setUser(user.getUserName());
				listResult.add(resourceDisplay);
			}
		} catch (SQLException e) {
			log.error(e.getMessage());
		}
		return listResult;
	}
	
	public String getNewResourcesName() {
		return newResourcesName;
	}

	public void setNewResourcesName(String newResourcesName) {
		this.newResourcesName = newResourcesName;
	}

	@Begin
	public void start() {
		log.info(" start");
	}
	
	@End
	public void end() {
		log.info(" end");
	}
}
